<template>
  <div>
    <div class="m_left">
      <div class="left_n" v-if="isAdmin">管理中心</div>
      <div class="left_n" v-if="!isAdmin">个人中心</div>
      <div class="left_m">
        <div class="left_m_t t_bg1">资讯中心</div>
        <ul>
          <li><a href="#" @click.prevent="toNewsList">所有资讯 </a></li>
          <li v-if="isAdmin">
            <a href="#" @click.prevent="showAddNewsForm">增加资讯 </a>
          </li>
        </ul>
      </div>
      <div class="left_m" v-if="isAdmin">
        <div class="left_m_t t_bg1">商品管理</div>
        <ul>
          <li><a href="#" @click.prevent="toProductList">所有商品</a></li>
          <li><a href="#" @click.prevent="toAddProduct">添加商品</a></li>
        </ul>
      </div>
      <div class="left_m">
        <div class="left_m_t t_bg1">订单中心</div>
        <ul>
          <li><a href="" @click.prevent="toUserOrderList">我的订单</a></li>
          <li><a href="" @click.prevent="toUserFavoriteList">我的收藏</a></li>
          <li><a href="#" @click.prevent="toUserAddress">收货地址</a></li>
        </ul>
      </div>
      <div class="left_m" v-if="isAdmin">
        <div class="left_m_t t_bg1">订单管理</div>
        <ul>
          <li><a href="#" @click.prevent="toProductOrderList">所有订单</a></li>
        </ul>
      </div>

      <div class="left_m">
        <div class="left_m_t t_bg2">会员中心</div>
        <ul>
          <li><a href="#" @click.prevent="toUserMsg">用户信息</a></li>
          <li v-if="isAdmin">
            <a href="#" @click.prevent="toUserList">用户列表</a>
          </li>
        </ul>
      </div>
      <div class="left_m" v-if="isAdmin">
        <div class="left_m_t t_bg4">分类管理</div>
        <ul>
          <li><a href="#" @click.prevent="toCategoryTree">查看分类</a></li>
        </ul>
      </div>
    </div>
    <!-- 新闻添加弹窗 -->
    <div class="modal-overlay" v-if="showAddModal">
      <div class="add-modal">
        <div class="modal-header">
          <h3>添加新闻咨询</h3>
          <button class="close-btn" @click="closeAddModal">&times;</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="submitAddForm">
            <!-- 标题输入框：移除原生 required，添加 placeholder -->
            <div class="form-group">
              <label for="add-title">标题</label>
              <input
                type="text"
                id="add-title"
                v-model="news.title"
                placeholder="请输入新闻标题"
              />
            </div>
            <!-- 内容文本域：移除原生 required，添加 placeholder -->
            <div class="form-group">
              <label for="add-content">内容</label>
              <textarea
                id="add-content"
                v-model="news.content"
                rows="5"
                placeholder="请输入新闻内容"
              ></textarea>
            </div>
            <div class="form-actions">
              <button type="button" class="cancel-btn" @click="closeAddModal">
                取消
              </button>
              <button type="submit" class="submit-btn" :disabled="isSubmitting">
                {{ isSubmitting ? "提交中..." : "提交" }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import { mapMutations } from "vuex";
export default {
  name: "CommonsMenu",
  data() {
    return {
      showAddModal: false,
      isSubmitting: false,
      news: {
        title: "",
        content: "",
      },
      isAdmin: sessionStorage.getItem("type") === "0", // 管理员判断（type=0为管理员）
    };
  },
  methods: {
    ...mapMutations(["setShowPage"]),
    showAddNewsForm() {
      this.showAddModal = true;
      // 打开弹窗时重置表单，避免残留上次输入
      this.news = { title: "", content: "" };
    },
    closeAddModal() {
      this.showAddModal = false;
      this.news = { title: "", content: "" }; // 关闭时清空表单
    },
    // 新闻添加提交（核心：新增非空校验）
    async submitAddForm() {
      // 1. 防止重复提交
      if (this.isSubmitting) return;

      // -------------------------- 非空校验（弹窗提示） --------------------------
      // 标题非空校验（去除首尾空格，避免全空格无效输入）
      if (!this.news.title.trim()) {
        this.$message.error("请输入新闻标题");
        return;
      }
      // 内容非空校验
      if (!this.news.content.trim()) {
        this.$message.error("请输入新闻内容");
        return;
      }

      // 2. 校验通过，开始提交
      this.isSubmitting = true;
      try {
        const response = await axios.post("/api/news/addNews", this.news);
        console.log("新闻添加响应:", response.data);
        
        // 3. 提交成功处理
        if (response.data.code === 200) {
          this.$message.success("新闻添加成功");
          this.closeAddModal(); // 关闭弹窗
          this.toNewsList(); // 跳转到新闻列表页，刷新数据
        } else {
          // 业务错误（如后端校验失败）
          this.$message.error(response.data.msg || "新闻添加失败");
        }
      } catch (error) {
        // 网络错误或请求异常
        console.error("新闻添加失败:", error);
        this.$message.error(
          error.response?.data?.msg || "请求失败，请稍后重试"
        );
      } finally {
        // 4. 无论成功/失败，结束提交状态
        this.isSubmitting = false;
      }
    },
    // 跳转新闻列表
    toNewsList() {
      this.$router.push({ name: "newsList" });
    },
    // 跳转商品列表
    toProductList() {
      this.$router.push({ name: "ProductList" });
    },
    // 跳转添加商品
    toAddProduct() {
      if (this.$route.name === "AddProduct") {
        // 已在添加商品页，调用子组件重置方法（若存在）
        const addProductComp = this.$router
          .getMatchedComponents()
          .find((comp) => comp.name === "AddProduct");
        if (addProductComp?.instance?.resetForm) {
          addProductComp.instance.resetForm();
        }
      } else {
        this.$router.push({ name: "AddProduct" });
      }
    },
    // 跳转用户列表（管理员）
    toUserList() {
      this.$router.push({ name: "userList" });
    },
    // 跳转分类管理（管理员）
    toCategoryTree() {
      this.$router.push({ name: "CategoryTree" });
    },
    // 跳转所有订单（管理员）
    toProductOrderList() {
      this.$router.push({ name: "ProductOrderList" });
    },
    // 跳转个人订单
    toUserOrderList() {
      this.$router.push({ name: "UserOrderList" });
    },
    // 跳转个人收藏
    toUserFavoriteList() {
      this.$router.push({ name: "UserFavoriteList" });
    },
    // 跳转收货地址
    toUserAddress() {
      this.$router.push({ name: "UserAddress" });
    },
    // 跳转用户信息
    toUserMsg() {
      this.$router.push({ name: "userMsg" });
    },
  },
  created() {
    // 冗余代码清理：isAdmin已在data中定义，无需重复赋值
    // this.type = sessionStorage.getItem("type") == 0 ? true : false;
  },
};
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.add-modal {
  background-color: white;
  border-radius: 8px;
  width: 650px;
  max-width: 90%;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.modal-header {
  padding: 16px 24px;
  border-bottom: 1px solid #e8e8e8;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  color: rgba(0, 0, 0, 0.85);
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: rgba(0, 0, 0, 0.45);
}

.close-btn:hover {
  color: rgba(0, 0, 0, 0.75);
}

.modal-body {
  padding: 24px;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
}

.form-group input,
.form-group textarea {
  width: 90%;
  padding: 8px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 14px;
}

.form-group textarea {
  resize: vertical;
  min-height: 100px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 24px;
}

.cancel-btn {
  padding: 8px 16px;
  background-color: #f5f5f5;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  cursor: pointer;
}

.cancel-btn:hover {
  background-color: #e6e6e6;
}

.submit-btn {
  padding: 8px 16px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.submit-btn:hover {
  background-color: #40a9ff;
}

.submit-btn:disabled {
  background-color: #bae7ff;
  cursor: not-allowed;
}
</style>